<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <button type="button" name="button" onclick="login()">login</button>
  <button type="button" name="button" onclick="getdata()">getdata</button>
</body>
<script type="text/javascript">

function login(){
  ajax({
    reqMethod:"post",
    reqData:JSON.stringify({
      name:"123",
      passwd:"123"
    }),
    reqHeader:{
      "content-type":"application/json"
    },
    reqURL:"http://127.0.0.1:3000/login",
    reqSuccess:function(data){
      console.log(data);
    }
  })
}

function getdata(){
  ajax({
    reqMethod:"get",
    reqURL:"http://127.0.0.1:3000/getdata",
    reqSuccess:function(data){
      console.log(data);
    }
  })
}



function ajax(obj){
  var reqURL=obj.reqURL;
  var reqMethod=obj.reqMethod||"get";
  var reqAsync=obj.reqAsync||true;
  var reqData=obj.reqData||"";//直接传数据不解析
  var reqHeader=obj.reqHeader;
  var reqSuccess=obj.reqSuccess;
  var reqError=obj.reqError;
  var reqBefore=obj.reqBefore;
  var reqUserName=obj.reqUserName||"";
  var reqUserPassWord=obj.reqUserPassWord||"";

  var req=new XMLHttpRequest();
  req.onreadystatechange=function(){
    if(req.readyState==4)
    {
      if(req.status==200){
        if(reqSuccess)reqSuccess(req.responseText);
      }else{
        if(reqError)reqError(req.responseText);
      }
    }
  };
  req.open(reqMethod,reqURL,reqAsync,reqUserName,reqUserPassWord);
  if(reqHeader){
    for(var head in reqHeader){
      req.setRequestHeader(head,reqHeader[head]);
    }
  }
  if(reqBefore)reqBefore(req);
  req.send(reqData);
}
</script>
</html>
